<template>
  <div>
    <n-card :content-style="{paddingBottom: '0px',paddingTop: '17px'}">
      <n-space>
        <n-form label-placement="left">
          <n-form-item label="人物数量 :" size="small">
            <n-tag v-for="tag in tagNum" v-model:checked="tag.checked" checkable @click="getOpenPoseList">
              {{ tag.label }}
            </n-tag>
          </n-form-item>
          <n-form-item label="人物姿势 :" size="small">
            <n-tag v-for="tag in tagList" v-model:checked="tag.checked" checkable @click="getOpenPoseList">
              {{ tag.label }}
            </n-tag>
          </n-form-item>
        </n-form>
      </n-space>
    </n-card>
    <n-card style="margin-top: 5px">
      <n-space justify="space-between">
        <n-button type="primary" style="margin-bottom: 10px;"
                  @click="resetForm() ;formTitle = '新增骨骼图'; addModalShow = true">
          <template #icon>
            <n-icon>
              <AddSharp/>
            </n-icon>
          </template>
          新增
        </n-button>

        <n-button type="info" style="margin-bottom: 10px;"
                  @click="syncData() ;">
          同步云端骨骼图
        </n-button>

      </n-space>

      <n-scrollbar
          :content-style="{padding: '5px 5px 5px 5px', height: clientHeight - (layoutHeaderHeight  + tabsHeight + 225) + 'px'}">
        <n-grid x-gap="4" y-gap="4" :cols="5" item-responsive responsive="screen">
          <n-gi v-for="openPose in openPoseList">
            <n-card>
              <template #cover>
                <div>
                  <n-image  :height="300" :object-fit="'cover'" v-if="openPose?.poseName"
                       :src="fileFunction.getOpenPoseImage(openPose?.poseName)">
                  </n-image>
                </div>
              </template>
              <template #action>
                <n-space justify="space-between">
                  <n-button v-if="props.mode!='choseOpenPose'" size="small" type="primary" @click="updateForm(openPose)">修改</n-button>
                  <n-button size="small" type="info" v-if="!client" @click="uploadToChuangTu(openPose)">上传图床</n-button>
                  <n-button v-if="props.mode!='choseOpenPose'" size="small" type="error" :loading="deleteLoading" @click="deleteOpenPose(openPose)">删除
                  </n-button>
                  <n-button v-if="props.mode=='choseOpenPose'" size="small" type='info' @click="props.choseOpenPose(openPose)">选择</n-button>
                </n-space>
              </template>
            </n-card>
          </n-gi>
        </n-grid>
      </n-scrollbar>
    </n-card>

    <n-drawer
        v-model:show="addModalShow"
        :width="600"
        :close-on-esc="false"
        :mask-closable="false">
      <n-drawer-content :title="formTitle" closable>
        <n-form ref="formRef" :model="openPoseForm">
          <n-form-item
              label="姿势名称"
              path="promptTitle"
          >
            <n-input v-model:value="openPoseForm.poseName" clearable/>
          </n-form-item>
          <n-form-item
              label="人物数量"
              path="peopleNumber"
          >
            <n-select
                :options="tagNum"
                v-model:value="openPoseForm.peopleNumber"
                clearable
            >
            </n-select>
          </n-form-item>
          <n-form-item
              label="姿势类型"
              path="poseType"
          >
            <n-select
                :options="tagList"
                multiple
                v-model:value="openPoseForm.poseTypeList"
                clearable
            >
            </n-select>
          </n-form-item>
<!--          <n-form-item-->
<!--              label="姿势描述"-->
<!--              path="poseDescription"-->
<!--          >-->
<!--            <n-input v-model:value="openPoseForm.poseDescription" clearable/>-->
<!--          </n-form-item>-->
<!--          <n-form-item label="资源选择" path="resourceId" v-if="formTitle!='编辑骨骼图'">-->
<!--            <n-select v-model:value="openPoseForm.resourceId" :options="resourceOption">-->
<!--            </n-select>-->
<!--          </n-form-item>-->
          <n-form-item :show-label="false" label="参考图片" path="negativePrompt" v-if="formTitle!='编辑骨骼图'">
            <n-card title="姿势图片" bordered>
              <template #header-extra>
<!--                <n-button size="small" type="primary" v-if="openPoseForm.poseExampleBackground" @click="createOpenPose" :loading="controlNetLoading">-->
<!--                  预处理-->
<!--                </n-button>-->
<!--                <n-button size="small" type="warning" style="margin-left: 5px;"-->
<!--                          @click="openPoseForm.poseExampleBackground=''; openPoseCreateVo.poseImage='';openPoseCreateVo.poseExampleImage=''"> 清除-->
<!--                </n-button>-->
              </template>
              <template #cover>
                <div>
                  <img
                      :style="{
                      width: canvasWidth + 'px',
                      height: canvasHeight + 'px'
                      }"
                      v-if="openPoseForm.poseExampleBackground"
                      :src="openPoseForm.poseExampleBackground"
                      alt=""
                      @load="handleImgLoad"/>
                  <img
                      :style="{
                        width: canvasWidth + 'px',
                        height: canvasHeight + 'px',
                        display:'flex',
                        justifyContent: 'center',
                        alignItems: 'center'
                      }"
                      v-if="openPoseCreateVo?.poseExampleImage"
                      :src="'data:image/jpeg;base64,'+ openPoseCreateVo?.poseExampleImage" alt="" @load="handleImgLoad"
                      class="fg-image">
                </div>
              </template>
              <n-empty description="未上传图片" v-if="!openPoseForm.poseExampleBackground">
                <template #extra>
                  <n-upload
                      :custom-request="customRequest"
                  >
                    <n-button>上传图片</n-button>
                  </n-upload>
                </template>
              </n-empty>
            </n-card>
          </n-form-item>
        </n-form>

        <template #footer>
          <n-button @click="addModalShow = false">取消</n-button>
          <n-button style="margin-left: 5px" type="primary" @click="submitForm" :loading="saveLoading">保存</n-button>
        </template>
      </n-drawer-content>
    </n-drawer>

    <n-modal  v-model:show="syncModalShow" @after-leave="getOpenPoseList" >
      <n-card
        style="width: 600px"
        title="同步进度"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <SyncDataSchdule v-if="syncTaskId" :taskId="syncTaskId"></SyncDataSchdule>
      </n-card>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import {h, onMounted, ref} from 'vue'
import {NButton, NTag, UploadCustomRequestOptions} from "naive-ui";
import Bus from '@/components/file/box/GlobalUploader/utils/bus.js'
import {storeToRefs} from "pinia";
import {useSystemStore} from "@/store/modules/useSystemStore";
import {AddSharp} from "@vicons/ionicons5";
import {openPoseController} from "@/api/controller/openpose/tagCategoryController"
import fileFunction from '@/libs/globalFunction/file.js'
import {resourceController} from "@/api/resource/resourceController.api";
import {storyBoardController} from "@/api/controller/story/storyBoard.api";
import {setting} from "@/config/setting";
import SyncDataSchdule from "@/components/syncData/syncDataSchdule.vue";
const {client} = setting
const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());
const openPoseList = ref([])
const addModalShow = ref(false)
const resourceOption = ref([])
const openPoseCreateVo = ref({
  poseImage: '',
  poseExampleImage: ''
})


// 设置canvas宽高
const canvasWidth = ref(400)
const canvasHeight = ref(400)
const syncModalShow = ref(false)
const syncTaskId = ref('')

const formTitle = ref('新增骨骼图')

const props = defineProps({
  mode: {
    type: String,
    default: 'create'
  },
  choseOpenPose :{
    type:Function,
    default:()=>{}
  }
})



const openPoseForm = ref({
  id: '',
  poseName: '',
  poseType: '',
  poseTypeList: [],
  poseDescription: '',
  poseExampleBackground: '',
  poseImage: '',
  poseExampleImage: '',
  peopleNumber: '',
  resourceId: ''
})

const resetForm = () => {
  openPoseForm.value = {
    id: '',
    poseName: '',
    poseType: '',
    poseDescription: '',
    poseExampleBackground: '',
    poseImage: '',
    poseExampleImage: '',
    peopleNumber: '',
    resourceId: '',
    poseTypeList: []
  }
  openPoseCreateVo.value = {
    poseImage: '',
    poseExampleImage: ''
  }
}

const tableLoading = ref(false)
const deleteLoading = ref(false)
const saveLoading = ref(false)
const controlNetLoading = ref(false)
const getOpenPoseList = () => {
  tableLoading.value = true
  const tags: any = []
  tagList.value.forEach((tag) => {
    if (tag.checked) {
      tags.push(tag.value)
    }
  })
  const queryTag = tags.join(',')

  const numTags: any = []
  tagNum.value.forEach((tag) => {
    if (tag.checked) {
      numTags.push(tag.value)
    }
  })
  const numTag = numTags.join(',')

  const param = {
    poseType: queryTag,
    peopleNumber: numTag
  }
  openPoseController.getOpenPoseList(param).then((res) => {
    tableLoading.value = false
    if (res.code === 200) {
      openPoseList.value = res.data
      openPoseList.value.forEach((item: any) => {
        item.poseTypeList = item.poseType.split(',')
      })
    }
  }).finally(() => {
    tableLoading.value = false
  })

}


const handleImgLoad = (e: any) => {
  const image = e.target;
  let image_new = new Image()
  image_new.src = image.src
  image_new.onload = function () {
    // 计算图片宽高比例
    let imgRatio = image_new.width / image_new.height
    if (image_new.width > 400
        || image_new.height > 400) {
      // 计算缩放后的宽高
      if (imgRatio > 1) {
        canvasWidth.value = 400
        canvasHeight.value = image_new.height / (image_new.width / 400)
      } else {
        // 图片比较宽
        canvasWidth.value = image_new.width / (image_new.height / 400)
        canvasHeight.value = 400
      }
    } else {
      canvasWidth.value = image_new.width
      canvasHeight.value = image_new.height
    }
  }
}

const customRequest = (uploadOption: UploadCustomRequestOptions) => {
  const reader = new FileReader();
  //@ts-ignore
  reader.readAsDataURL(uploadOption.file.file);
  reader.onloadend = () => {
    let image = new Image()
    image.src = reader.result
    //@ts-ignore
    openPoseForm.value.poseExampleBackground = reader.result
  };
}
onMounted(() => {
  getOpenPoseList()
  getResourceInfo()
})

const createOpenPose = () => {
  if(!openPoseForm.value.resourceId){
    window.$message.warning('请选择资源')
    return
  }

  controlNetLoading.value = true
  const param = {
    exampleImage: openPoseForm.value.poseExampleBackground,
    resourceId: openPoseForm.value.resourceId
  }
  openPoseController.createOpenPose(param).then((res) => {
    if (res.code === 200) {
      // openPoseForm.value.poseExampleImage = res.data
      openPoseCreateVo.value = res.data
    }
  }).finally(() => {
    controlNetLoading.value = false
  })
}

const submitForm = () => {
  if (openPoseForm.value.poseName === ''){
    window.$message.warning('请输入姿势名称')
    return
  }
  if (openPoseForm.value.poseExampleBackground === ''){
    window.$message.warning('请上传参考图片')
    return
  }
  saveLoading.value = true
  openPoseForm.value.poseExampleBackground = openPoseForm.value.poseExampleBackground.split(';base64,')[1]
  openPoseForm.value.poseType = openPoseForm.value.poseTypeList.join(',')
  openPoseController.addOpenPose(openPoseForm.value).then((res) => {
    if (res.code === 200) {
      addModalShow.value = false
      getOpenPoseList()
    }
  }).finally(() => {
    openPoseForm.value.poseExampleBackground = "data:image/png;base64," + openPoseForm.value.poseExampleBackground
    saveLoading.value = false
  })
}


const tagNum = ref([
  {
    label: '单人',
    checked: false,
    value: 'single'
  },
  {
    label: '双人',
    checked: false,
    value: 'double'
  },
  {
    label: '多人',
    checked: false,
    value: 'multiple'
  }
])


const tagList = ref([
  {
    label: '自定义',
    checked: false,
    value: 'custom'
  },
  {
    label: 'T型姿势',
    checked: false,
    value: 't-pose'
  },
  {
    label: '双臂交叉',
    checked: false,
    value: 'crossed Arms'
  },
  {
    label: '举起手臂',
    checked: false,
    value: 'raised Arms'
  },
  {
    label: '斜靠',
    checked: false,
    value: 'leaning'
  },
  {
    label: '屈伸',
    checked: false,
    value: 'flexing'
  },
  {
    label: '躺着',
    checked: false,
    value: 'laying'
  },
  {
    label: '起跳',
    checked: false,
    value: 'jumping'
  },
  {
    label: '跳舞',
    checked: false,
    value: 'dancing'
  },
  {
    label: '坐着',
    checked: false,
    value: 'sitting'
  },
  {
    label: '跪下',
    checked: false,
    value: 'kneeling'
  },
  {
    label: '站立',
    checked: false,
    value: 'standing'
  }
])

/***
 * 获取绘画资源
 */
const getResourceInfo = () => {
  resourceController.getSDResource('SD').then(res => {
    if (res.code === 200) {
      res.data.forEach((item: any) => {
        // @ts-ignore
        resourceOption.value.push({
          label: item.resourceName,
          value: item.id
        })
      })
      console.log(resourceOption.value)
    }
  })
}

const deleteOpenPose = (row: any) => {
  window.$dialog.warning({
    title: "温馨提醒",
    content: "是否删除该骨骼图?",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      deleteLoading.value = true
      openPoseController.deleteOpenPose(row.id).then(res => {
        if (res.code === 200) {
          window.$message.success(res.msg)
          getOpenPoseList()
        }
      }).finally(() => {
        deleteLoading.value = false
      })
    }
  })
}

const updateForm = (openPose:any) =>{
  openPoseForm.value = openPose
  formTitle.value = '编辑骨骼图'
  addModalShow.value = true
}


const syncData =() =>{
  openPoseController.syncData().then(res=>{
    if(res.code === 200){
      syncTaskId.value = res.data
      syncModalShow.value = true
    }
  })
}
const uploadToChuangTu = (openPose:any) => {
  openPoseController.uploadToChuangTu(openPose.id).then(res=>{
    if(res.code === 200){
      window.$message.success(res.msg)
    }
  })
}
</script>
<style scoped>
.fg-image {
  position: absolute; /* 让图片脱离常规文档流，并可进行绝对定位 */
  top: 0;
  left: 0;
  z-index: 2; /* 确保前景图片在上方 */
}
</style>
